'use strict';

/**
 * Config for the router
 */
angular.module('app').config(
    ['$stateProvider', '$urlRouterProvider', 'JQ_CONFIG', 'MODULE_CONFIG',function ($stateProvider,   $urlRouterProvider, JQ_CONFIG, MODULE_CONFIG) {
          
          
          $stateProvider.state('app.interface', {
              abstract: true,
              url: '/interface',
              templateUrl: 'modular/interface/tpl/interface.html',
              resolve: load( ['modular/interface/controllers/interfaceCtrl.js'] )
          })
          .state('app.interface.list', {
              url: '/index/{provider}',
              templateUrl: 'modular/interface/tpl/interface.list.html'
          })
          .state('app.interface.compose', {
              url: '/compose',
              templateUrl: 'modular/interface/tpl/interface.new.html',
              resolve: load( ['ngImgCrop'] )
          })
          .state('app.interface.pathnew', {
	          url: '/pathnew/{provider}',
	          templateUrl: 'modular/interface/tpl/interface.pathNew.html'
          })
          .state('app.interface.keynew', {
	          url: '/keynew/{provider}',
	          templateUrl: 'modular/interface/tpl/interface.keyNew.html'
          });


          function load(srcs, callback){
        	  return {
        	        deps: ['$ocLazyLoad', '$q',
        	          function( $ocLazyLoad, $q ){
        	            var deferred = $q.defer();
        	            var promise  = false;
        	            srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
        	            if(!promise){
        	              promise = deferred.promise;
        	            }
        	            angular.forEach(srcs, function(src) {
        	              promise = promise.then( function(){
        	                if(JQ_CONFIG[src]){
        	                  return $ocLazyLoad.load(JQ_CONFIG[src]);
        	                }
        	                angular.forEach(MODULE_CONFIG, function(module) {
        	                  if( module.name == src){
        	                    name = module.name;
        	                  }else{
        	                    name = src;
        	                  }
        	                });
        	                return $ocLazyLoad.load(name);
        	              } );
        	            });
        	            deferred.resolve();
        	            return callback ? promise.then(function(){ return callback(); }) : promise;
        	        }]
        	    }
          }
      }
    ]
  );
